package com.acoffee.gateway;

import com.acoffee.springcloud.common.entity.ResponseEntity;
import com.acoffee.springcloud.common.utils.JWTUtils;
import com.ctc.wstx.util.StringUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * @author acoffee
 * @create 2022-02-10 14:56
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    //GobalFilter拦截的核心方法
    //Mono: Gateway的底层是Netty, Nio不是Servlet的API
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("进入loginfilter");
        ServerHttpRequest request = exchange.getRequest();

        //某些路径可以放行
        if (request.getURI().getPath().contains("login")){
            System.out.println("登录页面直接放行");
            return chain.filter(exchange);
        }
        //token验证
        System.out.println("token验证");
        String token = request.getHeaders().getFirst("token");
        if (!StringUtils.isEmpty(token) && JWTUtils.verify(token)){
            System.out.println("token有效！放行");
            return chain.filter(exchange);
        }

        System.out.println("token无效,拦截请求");
        return exchange.getResponse().writeWith(Mono.just(getDataBuffer(exchange)));

    }


    DataBuffer getDataBuffer(ServerWebExchange exchange){
        ServerHttpResponse response = exchange.getResponse();
        ResponseEntity<String> result = new ResponseEntity<>(401, "auation", "先登录");
        //定义字节数组
        byte[] data=null;
        //序列化JSON
        try {
            data=new ObjectMapper().writeValueAsString(result).getBytes(StandardCharsets.UTF_8);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        //封装成Data缓冲
        DataBuffer dataBuffer=response.bufferFactory().wrap(data);
        //设置JSON响应头，否则中文乱码
        response.getHeaders().add("Content-Type","application/json;charset=utf-8");
        return dataBuffer;
    }
    @Override
    public int getOrder() {
        return 0;
    }
}
